package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.QServiceCenter;
import com.xinhe.web.entity.ServiceCenter;
import com.xinhe.web.reposity.ServiceCenterRepository;
import com.xinhe.web.request.ServiceCenterQuery;
import com.xinhe.web.util.Snowflake;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import java.util.Date;
import java.util.List;
import java.util.Optional;

//import com.xinhe.web.mapper.ServiceCenterMapper;

@Service
public class ServiceCenterService {
    @Value("${file.aliyun.endpoint}")
    private String endpoint;

    @Value("${file.aliyun.accessKeyId}")
    private String accessKeyId;

    @Value("${file.aliyun.accessKeySecret}")
    private String accessKeySecret;

    @Value("${file.aliyun.bucketName}")
    private String bucketName;
//    @Autowired
//    private ServiceCenterMapper serviceCenterMapper;
    /*@Autowired
    private IMemberDao memberDao;*/
//    @Autowired
    ServiceCenterRepository serviceCenterRepository;

    //初始化查询工厂
    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;
    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public QueryResults<ServiceCenter> pageServiceCenter(ServiceCenterQuery query) {
         int pageNum = query.getPageNum();
        //页大小
         int pageSize= query.getPageSize();
        QServiceCenter qServiceCenter = QServiceCenter.serviceCenter;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qServiceCenter.createTime.desc();
        if (StringUtils.isNotEmpty(query.getName())) {
            builder.and(qServiceCenter.name.contains(query.getName()));
        }
        if (StringUtils.isNotEmpty(query.getRemark())) {
            builder.and(qServiceCenter.remark.contains(query.getRemark()));
        }
        return queryFactory.select(
                Projections.bean(
                        ServiceCenter.class,
                        qServiceCenter.address,
                        qServiceCenter.name.as("name"),
                        qServiceCenter.latitude.as("latitude"),
                        qServiceCenter.createTime,
                        qServiceCenter.longitude.as("longitude")
                )
        ).from(qServiceCenter)
                .where(builder).offset(pageNum * pageSize).limit(pageSize).orderBy(sort).fetchResults();

    }

    public Result findByNotServiceCenter(Long serviceCenterId) {
        QServiceCenter qServiceCenter = QServiceCenter.serviceCenter;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qServiceCenter.id.ne(serviceCenterId));
        List<ServiceCenter> serviceCenterList = queryFactory.select(
                Projections.bean(
                        ServiceCenter.class,
                        qServiceCenter.address,
                        qServiceCenter.name.as("name"),
                        qServiceCenter.latitude.as("latitude"),
                        qServiceCenter.createTime,
                        qServiceCenter.longitude.as("longitude")
                )
        )
                .from(qServiceCenter)
                .where(builder)
                .orderBy(qServiceCenter.createTime.desc())
                .fetch();
        return Result.ok(serviceCenterList);
    }

    public Result saveModel(String name,String address,String longitude,String latitude) {
        ServiceCenter serviceCenter = new ServiceCenter();
        serviceCenter.setId(Snowflake.generateId());
        serviceCenter.setName(StringUtils.isNoneBlank(name)? name : "");
        serviceCenter.setAddress(StringUtils.isNoneBlank(address)? address : "");
        serviceCenter.setLongitude(StringUtils.isNoneBlank(longitude)? longitude : "");
        serviceCenter.setLatitude(StringUtils.isNoneBlank(latitude)? latitude : "");
        serviceCenterRepository.save(serviceCenter);
        return Result.ok();
    }
    public Result updateModel(Long id,String name,String address,String longitude,String latitude) {
        Optional<ServiceCenter> byId = serviceCenterRepository.findById(id);
        if (!byId.isPresent()){
            return Result.failed(10003,"记录不存在");
        }
        ServiceCenter serviceCenter = byId.get();
        serviceCenter.setName(StringUtils.isNoneBlank(name)? name : "");
        serviceCenter.setAddress(StringUtils.isNoneBlank(address)? address : "");
        serviceCenter.setLongitude(StringUtils.isNoneBlank(longitude)? longitude : "");
        serviceCenter.setLatitude(StringUtils.isNoneBlank(latitude)? latitude : "");
        serviceCenter.setUpdateTime(new Date());
        serviceCenterRepository.saveAndFlush(serviceCenter);
        return Result.ok();
    }
    public Result findById(Long id) {
        Optional<ServiceCenter> serviceCenterOptional = serviceCenterRepository.findById(id);
        return Result.ok(serviceCenterOptional.get());
    }
    @Transactional
    public Result updateMergeServiceCenter(Long serviceCenterId, List<Long> list) {
        /*if (!CollectionUtils.isEmpty(list)) {
            for (Long id : list) {
                List<Member> members = this.memberDao.findByServiceId(id);
                if (CollectionUtils.isNotEmpty(members)) {
                    for (Member member : members) {
                        member.setServiceId(serviceCenterId);
                        this.memberDao.update((BaseEntityImpl)member);
                    }
                }
                serviceCenterMapper.deleteServiceCenter(id);
            }
        }*/
        return Result.ok();
    }
    @Transactional
    public Result deleteServiceCenter(Long id) {
        /*List<Member> memberList = this.memberDao.findByServiceId(serviceCenterId);
        if (!CollectionUtils.isEmpty(memberList)) {
            return Result.failed(10002,"该服务中心已绑定会员");
        }*/
        //serviceCenterMapper.deleteServiceCenter(id);
        return Result.ok();
    }

}